﻿// <copyright file="ReportFormsController.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>

namespace MesAPI.Controllers.Maintenance
{
    using System;
    using System.Globalization;
    using System.Linq;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.EntityFrameworkCore;
    using PublicData;
    using PublicModelsAndEntities.Models.MaintenanceRecord;
    using XinjeMesProgram.Entities;
    using XinjeMesProgram.Entities.Maintenance;

    /// <summary>
    /// 报表 .
    /// </summary>
    [ApiController]
    [Authorize]
    public class ReportFormsController : ControllerBase
    {
#pragma warning disable SA1000 // Keywords should be spaced correctly
#pragma warning disable CS8601
#pragma warning disable CS8602 // 解引用可能出现空引用。
#pragma warning disable CS8604 // 引用类型参数可能为 null。
        private ResponseModel response = new();

        /// <summary>
        /// 维修处理率 .
        /// </summary>
        /// <param name="product_category">产品组 .</param>
        /// <param name="selectYear">选择年份 .</param>
        /// <returns> .</returns>
        [Route("api/v1/reportForms/getProcessRate")]
        [HttpGet]
        public ResponseModel GetProcessRate(string? product_category, int selectYear)
        {
            using var context = new FactoryMesContext();
            FormDatasModel result = new();
            try
            {
                result.DataType = new string[] { "来货量", "处理量", "处理率" };
                char[] spilt = new char[] { '-' };
                var query = from sr in context.MainsortRecord
                            where product_category != "全部" ? MainsortRecordState.Progroup[product_category] == sr.Product_Category : true
                            select new DateAndState
                            {
                                Time = DateTime.ParseExact(sr.WarehousingDate.Split(spilt)[0], "yyyy/MM/dd", CultureInfo.InvariantCulture),
                                State = sr.State,
                            };
                int[] laiHuo = new int[12];
                List<DateAndState> list = query.ToList();

                var laiHuoQuery = new List<DateAndState>(list);
                foreach (DateAndState date in laiHuoQuery.ToList())
                {
                    DateTime tempDate = date.Time;
                    for (int i = 0; i < laiHuo.Length; i++)
                    {
                        if (tempDate >= new DateTime(i == 0 ? selectYear - 1 : selectYear, 12 + i > 12 ? i : 12, 26) && tempDate <= new DateTime(selectYear, 1 + i, 25))
                        {
                            laiHuo[i]++;
                            break;
                        }
                    }
                }

                // 来货量返回
                result.Series.Add(new TypeData
                {
                    Name = "来货量",
                    Type = "bar",
                    Data = laiHuo,
                });

                int[] chuLi = new int[12];
                var chuLiQuery = list.Where(x => int.Parse(x.State) >= 3);
                foreach (DateAndState date in chuLiQuery.ToList())
                {
                    DateTime tempDate = date.Time;
                    for (int i = 0; i < laiHuo.Length; i++)
                    {
                        if (tempDate >= new DateTime(i == 0 ? selectYear - 1 : selectYear, 12 + i > 12 ? i : 12, 26) && tempDate <= new DateTime(selectYear, 1 + i, 25))
                        {
                            chuLi[i]++;
                            break;
                        }
                    }
                }

                result.Series.Add(new TypeData
                {
                    Name = "处理量",
                    Type = "bar",
                    Data = chuLi,
                });

                int[] chuLiLine = new int[12]; // 此数据用来存储处理量与来货量的百分比
                for (int i = 0; i < 12; i++)
                {
                    if (laiHuo[i] != 0)
                    {
                        chuLiLine[i] = (int)(((double)chuLi[i] / (double)laiHuo[i]) * 100);
                    }
                    else if (laiHuo[i] == 0 && chuLi[i] > 0)
                    {
                        chuLiLine[i] = 100;
                    }
                }

                result.Series.Add(new TypeData
                {
                    Name = string.Format("{0}%", "处理率"),
                    Type = "line",
                    YAxisIndex = 1,
                    Data = chuLiLine,
                });
            }
            catch (Exception)
            {
                this.response.SetError();
                return this.response;
            }

            this.response.SetData(result);
            return this.response;
        }

        /// <summary>
        /// 维修发货率.
        /// </summary>
        /// <param name="product_category">组别.</param>
        /// <param name="selectYear">年份.</param>
        /// <returns> .</returns>
        [Route("api/v1/reportForms/getDeliveryRate")]
        [HttpGet]
        public ResponseModel GetDeliveryRate(string? product_category, int selectYear)
        {
            using var context = new FactoryMesContext();
            FormDatasModel result = new();
            try
            {
                result.DataType = new string[] { "月提交发货总数", "月包装总数", "发货件数", "发货完成率" };
                char[] spilt = new char[] { '-' };
                var laiHuoQuery = from s in context.RepairProduct // MainsortRecord
                                  join d in context.Deliver
                                  on s.ProductId equals d.ProductId
                                  join m in context.MainsortRecord
                                  on s.ProductId equals m.ID
                                  where s.RepairCompletedTime != null && product_category != "全部" ? MainsortRecordState.Progroup[product_category] == m.Product_Category : true
                                  select new DateAndState
                                  {
                                      Time = s.RepairCompletedTime != null ? DateTime.Parse(s.RepairCompletedTime.ToString()) : DateTime.Parse("2021-06-21"),
                                      State = m.State,
                                      TimemS = d.PackagingTime != null ? DateTime.ParseExact(d.PackagingTime, "yyyy/MM/dd", CultureInfo.InvariantCulture) : null,
                                      Btime = d.DeliveryTime,
                                  };

                int[] tijiao = new int[12];
                List<DateAndState> tijiaoList = laiHuoQuery.ToList();

                // 每月提交数量
                foreach (DateAndState date in tijiaoList)
                {
                    DateTime? tempDate = date.Time;
                    for (int i = 0; i < tijiao.Length; i++)
                    {
                        if (tempDate >= new DateTime(i == 0 ? selectYear - 1 : selectYear, 12 + i > 12 ? i : 12, 26) && tempDate < new DateTime(selectYear, 1 + i, 26))
                        {
                            tijiao[i]++;
                            break;
                        }
                    }
                }

                result.Series.Add(new TypeData
                {
                    Name = "月提交发货总数",
                    Type = "bar",
                    Data = tijiao,
                });

                int[] faHuo = new int[12];
                foreach (DateAndState time in tijiaoList)
                {
                    if (time.TimemS != null)
                    {
                        for (int i = 0; i < faHuo.Length; i++)
                        {
                            if (time.Time >= new DateTime(i == 0 ? selectYear - 1 : selectYear, 12 + i > 12 ? i : 12, 26) && time.Time < new DateTime(selectYear, 1 + i, 26) &&
                                time.TimemS > new DateTime(i == 0 ? selectYear - 1 : selectYear, 12 + i > 12 ? i : 12, 25) && time.TimemS <= new DateTime(selectYear, 1 + i, 27))
                            {
                                faHuo[i]++;
                                break;
                            }
                        }
                    }
                }

                // 发货量
                result.Series.Add(new TypeData
                {
                    Name = "月包装总数",
                    Type = "bar",
                    Data = faHuo,
                });

                // var faHuoQuery = from d in context.Deliver
                //                 where d.DeliveryTime >= new DateTime(selectYear - 1, 12, 26) && d.DeliveryTime < new DateTime(selectYear, 12, 26)
                //                 select d.DeliveryTime;
                int[] baozhuang = new int[12];
                foreach (DateAndState time in tijiaoList)
                {
                    if (time.Btime != null)
                    {
                        for (int i = 0; i < baozhuang.Length; i++)
                        {
                            if (time.Time >= new DateTime(i == 0 ? selectYear - 1 : selectYear, 12 + i > 12 ? i : 12, 26) && time.Time < new DateTime(selectYear, 1 + i, 26) &&
                                time.Btime >= new DateTime(i == 0 ? selectYear - 1 : selectYear, 12 + i > 12 ? i : 12, 26) && time.Btime < new DateTime(selectYear, 1 + i, 28))
                            {
                                baozhuang[i]++;
                                break;
                            }
                        }
                    }
                }

                result.Series.Add(new TypeData
                {
                    Name = "月发货总数",
                    Type = "bar",
                    Data = baozhuang,
                });

                int[] delivery = new int[12];
                foreach (DateAndState time in tijiaoList)
                {
                    for (int i = 0; i < delivery.Length; i++)
                    {
                        DateTime? tempDate = time.Time;
                        DateTime? btime1 = time.Btime == null ? DateTime.Now : time.Btime;
                        if (time.TimemS != null && time.Btime != null)
                        {
                            if (tempDate >= new DateTime(i == 0 ? selectYear - 1 : selectYear, 12 + i > 12 ? i : 12, 26) &&
                                tempDate < new DateTime(selectYear, 1 + i, 26) && (btime1 - time.TimemS).Value.Days > 2)
                            {
                                delivery[i]++;
                                break;
                            }
                        }
                    }
                }

                result.Series.Add(new TypeData
                {
                    Name = "包装超期数",
                    Type = "bar",
                    Data = delivery,
                });

                int[] deliveryCompletionRate = new int[12];
                for (int i = 0; i < deliveryCompletionRate.Length; i++)
                {
                    if (tijiao[i] != 0)
                    {
                        deliveryCompletionRate[i] = (int)((double)delivery[i] / (double)tijiao[i] * 100);
                    }
                }

                result.Series.Add(new TypeData
                {
                    Name = string.Format("{0}%", "包装超期率"),
                    Type = "line",
                    YAxisIndex = 1,
                    Data = deliveryCompletionRate,
                });
                this.response.SetData(result);
            }
            catch (Exception)
            {
                this.response.SetError();
                return this.response;
            }

            return this.response;
        }

        /// <summary>
        /// 获取所有客户列表.
        /// </summary>
        /// <param name="name">组别 .</param>
        /// <returns> .</returns>
        [Route("api/v1/reportForms/obtainCustomerList")]
        [HttpGet]
        public ResponseModel ObtainCustomerList(string? name)
        {
            using var context = new FactoryMesContext();
            var res = context.MainsortRecord.Where(x => x.CustomerLevel < 3 && (name != string.Empty ? x.Name.Contains(name) : true)).Select(x => x.Name).Distinct().ToList();
            List<ValueAndLabel> result = new();
            for (int i = 0; i < res.Count; i++)
            {
                result.Add(new ValueAndLabel(res[i], res[i], res[i]));
            }

            this.response.SetData(result);
            return this.response;
        }

        /// <summary>
        /// 维修超期率.
        /// </summary>
        /// <param name="pname">组别 .</param>
        /// <param name="customer">客户名称 .</param>
        /// <param name="selectYear">年份 .</param>
        /// <returns> .</returns>
        [Route("api/v1/reportForms/getOverdueRate")]
        [HttpGet]
        public ResponseModel GetOverdueRate(string? pname, string? customer, int selectYear)
        {
            using var context = new FactoryMesContext();
            FormDatasModel result = new();
            try
            {
                result.DataType = new string[] { "收货数", "正常", "超期", "超期率" };
                List<string> shouHuos = new();
                if (customer == string.Empty && pname == "所有")
                {
                    var query = from m in context.MainsortRecord
                                select m.WarehousingDate;
                    shouHuos = query.ToList();
                }
                else
                {
                    var query = from m in context.MainsortRecord
                                where m.Name.Contains(customer) && (pname == "所有" ? true : m.Product_Category == pname)
                                select m.WarehousingDate;

                    shouHuos = query.ToList();
                }

                int[] faHuo = new int[12];
                char[] spilt = new char[] { '-' };
                foreach (string date in shouHuos)
                {
                    DateTime tempDate = DateTime.ParseExact(date.Split(spilt)[0], "yyyy/M/d", CultureInfo.InvariantCulture);
                    for (int i = 0; i < faHuo.Length; i++)
                    {
                        if (tempDate >= new DateTime(i == 0 ? selectYear - 1 : selectYear, 12 + i > 12 ? i : 12, 26) && tempDate <= new DateTime(selectYear, 1 + i, 26))
                        {
                            faHuo[i]++;
                            break;
                        }
                    }
                }

                result.Series.Add(new TypeData
                {
                    Name = "收货数",
                    Type = "bar",
                    Data = faHuo,
                });

                List<TwoDate> overdueList = new();
                if (customer == string.Empty && pname == "所有")
                {
                    var overdueQuery = from m in context.MainsortRecord
                                       join r in context.Deliver
                                       on m.ID equals r.ProductId
                                       select new TwoDate
                                       {
                                           startTime = DateTime.ParseExact(m.WarehousingDate.Split(spilt)[0], "yyyy/M/d", CultureInfo.InvariantCulture),
                                           endTime = (DateTime)(r.DeliveryTime == null ? DateTime.Now : r.DeliveryTime),
                                       };
                    overdueList = overdueQuery.ToList();
                }
                else
                {
                    var overdueQuery = from m in context.MainsortRecord
                                       join r in context.Deliver
                                       on m.ID equals r.ProductId
                                       where m.Name.Contains(customer) && (pname == "所有" ? true : m.Product_Category == pname)
                                       select new TwoDate
                                       {
                                           startTime = DateTime.ParseExact(m.WarehousingDate.Split(spilt)[0], "yyyy/M/d", CultureInfo.InvariantCulture),
                                           endTime = (DateTime)(r.DeliveryTime == null ? DateTime.Now : r.DeliveryTime),
                                       };
                    overdueList = overdueQuery.ToList();
                }

                int[] unOverdue = new int[12];
                foreach (TwoDate two in overdueList)
                {
                    for (int i = 0; i < unOverdue.Length; i++)
                    {
                        if (two.startTime > new DateTime(i == 0 ? selectYear - 1 : selectYear, 12 + i > 12 ? i : 12, 26) && two.startTime <= new DateTime(selectYear, 1 + i, 26) && (two.endTime - two.startTime).Value.Days <= 7)
                        {
                            unOverdue[i]++;
                            break;
                        }
                    }
                }

                result.Series.Add(new TypeData
                {
                    Name = "正常",
                    Type = "bar",
                    Data = unOverdue,
                });

                int[] overdue = new int[12];
                int[] overdueRate = new int[12];
                for (int i = 0; i < overdue.Length; i++)
                {
                    overdue[i] = faHuo[i] - unOverdue[i];
                    if (faHuo[i] != 0)
                    {
                        overdueRate[i] = (int)((double)overdue[i] / (double)faHuo[i] * 100);
                    }
                    else if (faHuo[i] == 0 && overdue[i] > 0)
                    {
                        overdueRate[i] = 100;
                    }
                }

                result.Series.Add(new TypeData
                {
                    Name = "超期",
                    Type = "bar",
                    Data = overdue,
                });
                result.Series.Add(new TypeData
                {
                    Name = "超期率",
                    Type = "line",
                    YAxisIndex = 1,
                    Data = overdueRate,
                });
                this.response.SetData(result);
            }
            catch (Exception e)
            {
                this.response.SetError(e.Message);
                return this.response;
            }

            return this.response;
        }

        /// <summary>
        /// 收费达成率 .
        /// </summary>
        /// <param name="product_category">产品组 .</param>
        /// <param name="selectYear">选择年份 .</param>
        /// <returns> .</returns>
        [Route("api/v1/reportForms/getFeeAchievement")]
        [HttpGet]
        public ResponseModel GetFeeAchievement(string? product_category, int selectYear)
        {
            using var context = new FactoryMesContext();
            FormDatasModel result = new();
            result.DataType = new string[] { "收费总数", "已收到", "收费达成率" };
            var q = from sr in context.MainsortRecord
                    join c in context.MaintenanceCost
                    on sr.ID equals c.ID
                    where product_category == "全部" ? true : sr.Product_Category.Equals(MainsortRecordState.Progroup[product_category]) // && c.Receivable != null
                    select new TwoDate
                    {
                        startTime = c.ApplyTime,
                        endTime = c.UnlockTime,
                    };
            List<TwoDate> query = q.ToList();
            int[] receive = new int[12];
            int[] receiveTotal = new int[12];
            foreach (TwoDate two in query)
            {
                if (two.startTime != null)
                {
                    for (int i = 0; i < receiveTotal.Count(); i++)
                    {
                        if (two.startTime > new DateTime(i == 0 ? selectYear - 1 : selectYear, 12 + i > 12 ? i : 12, 26) && two.startTime <= new DateTime(selectYear, 1 + i, 26))
                        {
                            receiveTotal[i]++;
                            break;
                        }
                    }
                }

                if (two.endTime != null)
                {
                    for (int i = 0; i < receive.Count(); i++)
                    {
                        if (two.endTime > new DateTime(i == 0 ? selectYear - 1 : selectYear, 12 + i > 12 ? i : 12, 26) && two.endTime <= new DateTime(selectYear, 1 + i, 26) && (two.startTime - two.endTime).Value.Days <= 30)
                        {
                            receive[i]++;
                            break;
                        }
                    }
                }
            }

            int[] feeAchievementRate = new int[12];
            for (int i = 0; i < feeAchievementRate.Length; i++)
            {
                if (receiveTotal[i] != 0)
                {
                    feeAchievementRate[i] = (int)((double)receive[i] / (double)receiveTotal[i] * 100);
                }
                else if (receiveTotal[i] == 0 && receive[i] > 0)
                {
                    feeAchievementRate[i] = 100;
                }
            }

            result.Series.Add(new TypeData
            {
                Name = "收费总数",
                Type = "bar",
                Data = receiveTotal,
            });
            result.Series.Add(new TypeData
            {
                Name = "已收到",
                Type = "bar",
                Data = receive,
            });
            result.Series.Add(new TypeData
            {
                Name = "收费达成率",
                Type = "line",
                YAxisIndex = 1,
                Data = feeAchievementRate,
            });
            this.response.SetData(result);
            return this.response;
        }

        /// <summary>
        /// 维修时效性.
        /// </summary>
        /// <param name="pname">组别.</param>
        /// <param name="customer">2.</param>
        /// <param name="selectYear">选择年份.</param>
        /// <returns>返回.</returns>
        [Route("api/v1/reportForms/maintenanceTimeliness")]
        [HttpGet]
        public ResponseModel MaintenanceTimeliness(string? pname, string? customer, int selectYear)
        {
            using var context = new FactoryMesContext();
            FormDatasModel result = new();
            DateTime firstDate = new(selectYear - 1, 12, 26);
            DateTime endDate = new(selectYear, 12, 26);
            result.DataType = new string[] { "总发货数", "时效内发货数", "三日内发货数", "时效内发货率", "三日内发货率" };
            try
            {
                var query = from rp in context.RepairProduct
                            join d in context.Deliver
                            on rp.ProductId equals d.ProductId
                            join m in context.MainsortRecord
                            on rp.ProductId equals m.ID
                            where m.Name.Contains(customer) && (pname == "所有" ? true : m.Product_Category == pname)
                            select new TwoDate
                            {
                                startTime = rp.RepairCompletedTime,
                                endTime = d.DeliveryTime,
                            };
                List<TwoDate> list = query.ToList();
                int[] totalShipments = new int[12];
                int[] ageingShipments = new int[12];
                int[] threeDaysShipments = new int[12];
                foreach (TwoDate date in list)
                {
                    for (int i = 0; i < totalShipments.Length; i++)
                    {
                        if (date.endTime >= new DateTime(i == 0 ? selectYear - 1 : selectYear, 12 + i > 12 ? i : 12, 26) && date.endTime <= new DateTime(selectYear, 1 + i, 26))
                        {
                            totalShipments[i]++;
                            if ((date.endTime - date.startTime).Value.Days <= 3)
                            {
                                threeDaysShipments[i]++;
                            }

                            if ((date.endTime - date.startTime).Value.Days <= 9)
                            {
                                ageingShipments[i]++;
                            }
                        }
                    }
                }

                int[] ageingShipmentsRate = new int[12];
                int[] threeDaysShipmentsRate = new int[12];
                for (int i = 0; i < totalShipments.Length; i++)
                {
                    if (totalShipments[i] != 0)
                    {
                        ageingShipmentsRate[i] = (int)((double)ageingShipments[i] / (double)totalShipments[i] * 100);
                        threeDaysShipmentsRate[i] = (int)((double)threeDaysShipments[i] / (double)totalShipments[i] * 100);
                    }
                    else if (totalShipments[i] == 0 && ageingShipments[i] > 0)
                    {
                        ageingShipmentsRate[i] = 100;
                    }
                    else if (totalShipments[i] == 0 && threeDaysShipments[i] > 0)
                    {
                        threeDaysShipmentsRate[i] = 100;
                    }
                }

                result.Series.Add(new TypeData
                {
                    Name = "总发货数",
                    Type = "bar",
                    Data = totalShipments,
                });
                result.Series.Add(new TypeData
                {
                    Name = "时效内发货数",
                    Type = "bar",
                    Data = ageingShipments,
                });
                result.Series.Add(new TypeData
                {
                    Name = "三日内发货数",
                    Type = "bar",
                    Data = threeDaysShipments,
                });
                result.Series.Add(new TypeData
                {
                    Name = "时效内发货率%",
                    Type = "line",
                    YAxisIndex = 1,
                    Data = ageingShipmentsRate,
                });
                result.Series.Add(new TypeData
                {
                    Name = "三日内发货率%",
                    Type = "line",
                    YAxisIndex = 1,
                    Data = threeDaysShipmentsRate,
                });
                this.response.SetData(result);
            }
            catch (Exception)
            {
                this.response.SetError();
                return this.response;
            }

            return this.response;
        }

        /// <summary>
        /// 工程师维修数量 .
        /// </summary>
        /// <param name="data">产品组 .</param>
        /// <returns> .</returns>
        [Route("api/v1/reportForms/engineerRepairQuantity")]
        [HttpGet]
        public ResponseModel EngineerRepairQuantity(string? data)
        {
            using var context = new FactoryMesContext();
            FormDatasModel result = new();
            try
            {
                var query = from m in context.MainsortRecord
                            join rp in context.RepairProduct
                            on m.ID equals rp.ProductId
                            where ((data == null || data == string.Empty) ? true : MainsortRecordState.Progroup[data] == m.Product_Category)
                            && (rp.RepairCompletedTime == null ?
                            false : DateTime.Now.Year == rp.RepairCompletedTime.Value.Year
                            ? DateTime.Now.Month == 1 ?
                            rp.RepairCompletedTime.Value.Hour + 1 == DateTime.Now.Hour ?
                            rp.RepairCompletedTime.Value.Month == 12 ? rp.RepairCompletedTime.Value.Day > 25 : false : false : DateTime.Now.Month == rp.RepairCompletedTime.Value.Month && DateTime.Now.Day <= 25 ?
                            rp.RepairCompletedTime.Value.Day <= 25 : DateTime.Now.Day > 25 ? DateTime.Now.Month == rp.RepairCompletedTime.Value.Month && rp.RepairCompletedTime.Value.Day > 25 : DateTime.Now.Month - 1 == rp.RepairCompletedTime.Value.Month ? rp.RepairCompletedTime.Value.Day > 25 : false : false)
                            && new string[] { "6", "7", "8" }.Contains(m.State)
                            select m.AssignPersonnelUserId;
                Dictionary<string, int> map = new();
                foreach (string u in query.ToList())
                {
                    if (!map.TryAdd(u, 1))
                    {
                        map[u] += 1;
                    }
                }

                List<string> engineers = new();
                List<int> repairQuantity = new();
                foreach (string uid in map.Keys.ToArray())
                {
                    engineers.Add(context.MesUserRole.FirstOrDefault(x => x.ID == uid).UserName);
                    repairQuantity.Add(map[uid]);
                }

                result.XAxisName = engineers.ToArray();
                result.DataType = new string[] { "数量" };
                result.Series.Add(new TypeData
                {
                    Name = "数量",
                    Type = "bar",
                    Data = repairQuantity.ToArray(),
                });
                this.response.SetData(result);
            }
            catch (Exception e)
            {
                this.response.SetError(e.Message);
                return this.response;
            }

            return this.response;
        }

        /// <summary>
        /// 维修正常完成率 .
        /// </summary>
        /// <param name="product_category">产品组 .</param>
        /// <param name="selectYear">选择年份 .</param>
        /// <returns> .</returns>
        [Route("api/v1/reportForms/Maintenancecompletion")]
        [HttpGet]
        public ResponseModel Maintenancecompletion(string? product_category, int selectYear)
        {
            using var context = new FactoryMesContext();
            FormDatasModel result = new();
            try
            {
                result.DataType = new string[] { "处理量", "维修完成量(5天)", "正常完成率" };
                char[] spilt = new char[] { '-' };
                var query = from sr in context.MainsortRecord
                            join rp in context.RepairProduct
                              on sr.ID equals rp.ProductId into rpGroup
                            from rp in rpGroup.DefaultIfEmpty()
                            where product_category != "全部" ? MainsortRecordState.Progroup[product_category] == sr.Product_Category : true
                            select new DateAndState
                            {
                                Time = DateTime.ParseExact(sr.WarehousingDate.Split(spilt)[0], "yyyy/MM/dd", CultureInfo.InvariantCulture),
                                State = sr.State,
                                Timem = rp.RepairCompletedTime,
                            };

                List<DateAndState> list = query.ToList();  // 当月总数据。
                int[] laiHuo = new int[12];

                // var laiHuoQuery = new List<DateAndState>(list);
                var chuLiQuery = list.Where(x => int.Parse(x.State) >= 3);
                foreach (DateAndState date in chuLiQuery.ToList())
                {
                    DateTime tempDate = date.Time;
                    for (int i = 0; i < laiHuo.Length; i++)
                    {
                        if (tempDate >= new DateTime(i == 0 ? selectYear - 1 : selectYear, 12 + i > 12 ? i : 12, 26) && tempDate <= new DateTime(selectYear, 1 + i, 25))
                        {
                            laiHuo[i]++;
                            break;
                        }
                    }
                }

                result.Series.Add(new TypeData
                {
                    Name = "处理量",
                    Type = "bar",
                    Data = laiHuo,
                });

                int[] chuLi = new int[12];
                var repairQuery = list.Where(x => x.Timem != null);
                foreach (DateAndState date in repairQuery.ToList())
                {
                    DateTime tempDate = date.Time;
                    for (int i = 0; i < laiHuo.Length; i++)
                    {
                        if (tempDate >= new DateTime(i == 0 ? selectYear - 1 : selectYear, 12 + i > 12 ? i : 12, 26) && tempDate <= new DateTime(selectYear, 1 + i, 25) &&
                            ((DateTime)date.Timem - tempDate).Days <= 5)
                        {
                            chuLi[i]++;
                            break;
                        }
                    }
                }

                result.Series.Add(new TypeData
                {
                    Name = "维修完成量(5天)",
                    Type = "bar",
                    Data = chuLi,
                });

                int[] chuLiLine = new int[12]; // 此数据用来存储处理量与来货量的百分比
                for (int i = 0; i < 12; i++)
                {
                    if (laiHuo[i] != 0)
                    {
                        chuLiLine[i] = (int)(((double)chuLi[i] / (double)laiHuo[i]) * 100);
                    }
                    else if (laiHuo[i] == 0 && chuLi[i] > 0)
                    {
                        chuLiLine[i] = 100;
                    }
                }

                result.Series.Add(new TypeData
                {
                    Name = string.Format("{0}%", "正常完成率"),
                    Type = "line",
                    YAxisIndex = 1,
                    Data = chuLiLine,
                });
            }
            catch (Exception)
            {
                this.response.SetError();
                return this.response;
            }

            this.response.SetData(result);
            return this.response;
        }

        /// <summary>
        /// 二次维修数量 .
        /// </summary>
        /// <param name="pname">组别 .</param>
        /// <param name="start">开始时间 .</param>
        /// <param name="end">结束时间 .</param>
        /// <returns> .</returns>
        [Route("api/v1/reportForms/secondaryMaintenance")]
        [HttpGet]
        public ResponseModel SecondaryMaintenance(string pname, string start, string end)
        {
            using var context = new FactoryMesContext();

            DateTime startTime = DateTime.Parse(start);
            DateTime endTime = DateTime.Parse(end);
            try
            {
                if (pname == "所有")
                {
                    string sql = string.Format($"select ID,Product_Category,One_Dimensional_Code from MainsortRecord where CONVERT(datetime,substring(WarehousingDate,0,charindex('-',WarehousingDate)),111)<='{end}' and CONVERT(datetime,substring(WarehousingDate,0,charindex('-',WarehousingDate)),111)>='{start}'");
                    var query = context.MainsortRecord.FromSqlRaw(sql).Select(x => new ValueAndLabel(x.Product_Category, x.ID, x.One_Dimensional_Code)).ToList();
                    int two = 0, three = 0, four = 0;
                    var querya = query.GroupBy(b => b.ODC).Where(g => g.Count() == 2).SelectMany(g => g).ToList();
                    var querya1 = query.GroupBy(b => b.ODC).Where(g => g.Count() == 3).SelectMany(g => g).ToList();

                    two = (querya.Where(x => x.Value == "生产二部").Count() / 2) + (querya1.Where(x => x.Value == "生产二部").Count() / 3);
                    three = (querya.Where(x => x.Value == "生产三部").Count() / 2) + (querya1.Where(x => x.Value == "生产三部").Count() / 3);
                    four = (querya.Where(x => x.Value == "生产四部").Count() / 2) + (querya1.Where(x => x.Value == "生产四部").Count() / 3);

                    FormDatasModel result = new();
                    result.XAxisName = new string[] { "生产二部", "生产三部", "生产四部" };
                    result.DataType = new string[] { "数量" };
                    result.Series.Add(new TypeData
                    {
                        Name = "数量",
                        Type = "bar",
                        Data = new int[] { two, three, four },
                    });
                    this.response.SetData(result);
                }
                else
                {
                    char[] spilt = new char[] { '-' };
                    var query = from m in context.MainsortRecord
                                select new MRD
                                {
                                    Time = DateTime.ParseExact(m.WarehousingDate.Substring(0, 10), "yyyy/MM/dd", CultureInfo.InvariantCulture),
                                    One_Dimensional_Code = m.One_Dimensional_Code,
                                    assignPersonnel = context.MesUserRole.FirstOrDefault(x => x.ID == m.AssignPersonnelUserId).UserName ?? string.Empty,
                                    product_category = m.Product_Category,
                                };

                    List<string> name = new();

                    List<MRD> list = query.Where(x => x.product_category == pname).ToList();
                    DateTime timea = DateTime.ParseExact(end, "yyyy-MM-dd", CultureInfo.InvariantCulture);
                    DateTime timeb = DateTime.ParseExact(start, "yyyy-MM-dd", CultureInfo.InvariantCulture);
                    var c = list.Where(x => DateTime.Compare(x.Time, timeb) >= 0 && DateTime.Compare(x.Time, timea) <= 0).ToList();
                    var list1 = c.GroupBy(b => b.One_Dimensional_Code).Where(g => g.Count() == 2).SelectMany(g => g).ToList();  // 二次维修
                    var list3 = c.GroupBy(b => b.One_Dimensional_Code).Where(g => g.Count() == 2).SelectMany(g => g).Select(x => x.One_Dimensional_Code).Distinct().ToList(); // 序列号
                    var list2 = c.GroupBy(b => b.One_Dimensional_Code).Where(g => g.Count() == 3).SelectMany(g => g).ToList();  // 三次维修
                    var list4 = c.GroupBy(b => b.One_Dimensional_Code).Where(g => g.Count() == 3).SelectMany(g => g).Select(x => x.One_Dimensional_Code).Distinct().ToList(); // 序列号
                    var res = context.MesUserRole.Select(x => x.UserName).Distinct().ToList();

                    foreach (var item in res)
                    {
                        if (list1.Where(x => x.assignPersonnel == item).Count() > 0)
                        {
                            name.Add(item);
                        }
                    }

                    name.Add("重复登记");
                    int[] sex = new int[name.Count];  // 存放数量

                    foreach (var item in list3)
                    {
                        var ta = list1.Where(x => x.One_Dimensional_Code == item).ToList();
                        if (ta[0].Time == ta[1].Time)
                        {
                            sex[name.Count - 1]++;
                        }

                        if (DateTime.Compare(ta[0].Time, ta[1].Time) < 0)
                        {
                            for (int i = 0; i < name.Count; i++)
                            {
                                if (name[i] == ta[0].assignPersonnel)
                                {
                                    sex[i]++;
                                }
                            }
                        }
                        else
                        {
                            for (int i = 0; i < name.Count; i++)
                            {
                                if (name[i] == ta[1].assignPersonnel)
                                {
                                    sex[i]++;
                                }
                            }
                        }
                    }
                    ///////////////////////////////////////////////////////////////////////
                    foreach (var item in list4)
                    {
                        var ta = list2.Where(x => x.One_Dimensional_Code == item).ToList();
                        if (DateTime.Compare(ta[0].Time, ta[1].Time) < 0)
                        {
                            if (DateTime.Compare(ta[2].Time, ta[0].Time) < 0)
                            {
                                for (int i = 0; i < name.Count; i++)
                                {
                                    if (name[i] == ta[2].assignPersonnel)
                                    {
                                        sex[i]++;
                                    }
                                }
                            }
                            else
                            {
                                for (int i = 0; i < name.Count; i++)
                                {
                                    if (name[i] == ta[0].assignPersonnel)
                                    {
                                        sex[i]++;
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (DateTime.Compare(ta[2].Time, ta[1].Time) < 0)
                            {
                                for (int i = 0; i < name.Count; i++)
                                {
                                    if (name[i] == ta[2].assignPersonnel)
                                    {
                                        sex[i]++;
                                    }
                                }
                            }
                            else
                            {
                                for (int i = 0; i < name.Count; i++)
                                {
                                    if (name[i] == ta[1].assignPersonnel)
                                    {
                                        sex[i]++;
                                    }
                                }
                            }
                        }
                    }

                    string[] names = name.ToArray();
                    FormDatasModel result = new();
                    result.XAxisName = names;
                    result.DataType = new string[] { "数量" };
                    result.Series.Add(new TypeData
                    {
                        Name = "数量",
                        Type = "bar",
                        Data = sex,
                    });
                    this.response.SetData(result);
                }
            }
            catch (Exception e)
            {
                this.response.SetError(e.Message);
                return this.response;
            }

            return this.response;
        }

        // foreach (int i in mapTwo.Values.ToArray())
        // {
        //    if (i > 0)
        //    {
        //        two++;
        //    }
        // }

        // foreach (int i in mapThree.Values.ToArray())
        // {
        //    if (i > 0)
        //    {
        //        three++;
        //    }
        // }

        // foreach (int i in mapFour.Values.ToArray())
        // {
        //    if (i > 0)
        //    {
        //        four++;
        //    }
        // }
    }
}
